package com.lablzh.gdxy.service.impl;

import com.lablzh.gdxy.component.UserDetailsUtil;
import com.lablzh.gdxy.entity.admin.*;
import com.lablzh.gdxy.entity.assistant.Assistant;
import com.lablzh.gdxy.entity.course.Course;
import com.lablzh.gdxy.entity.design.Design;
import com.lablzh.gdxy.entity.practice.Practice;
import com.lablzh.gdxy.repository.admin.*;
import com.lablzh.gdxy.repository.assistant.AssistantRepository;
import com.lablzh.gdxy.repository.course.CourseRepository;
import com.lablzh.gdxy.repository.design.DesignRepository;
import com.lablzh.gdxy.repository.practice.PracticeRepository;
import com.lablzh.gdxy.service.ParametersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;
import java.util.*;


@Service
public class ParametersServiceImpl implements ParametersService {
    @Autowired
    private ParameterRepository parameterRepository;
    @Autowired
    private TopicNumberRepository topicNumberRepository;
    @Autowired
    private ColumnRepository columnRepository;
    @Autowired
    private SubjectRepository subjectRepository;
    @Autowired
    private CategoryRepository categoryRepository;
    @Autowired
    private PracticeRepository practiceRepository;
    @Autowired
    private DesignRepository designRepository;
    @Autowired
    private AssistantRepository assistantRepository;
    @Autowired
    private CourseRepository courseRepository;
    @Autowired
    private UserDetailsUtil userDetailsUtil;

    @Override
    public Map getCourseMiniCategory(String courseCategory) {
        List<Parameter> parameters = parameterRepository.findAllByCourseCategory(courseCategory, Sort.by(Sort.Direction.DESC, "id"));
        Map<String, Object> data = new HashMap<>();
        List<String> miniCategoryList = new ArrayList<>();

        for (Parameter parameter : parameters) {
          //  System.out.println(parameter.getCourseMiniCategory());
            miniCategoryList.add(parameter.getCourseMiniCategory());
        }
        data.put("miniCategory", miniCategoryList);
        return data;
    }

    @Override
    public Map<String, Object> getCourseParameterByUsername(String username, Integer page) {
        Parameter parameter = new Parameter();
        parameter.setResTeacherUsername(username);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("resTeacherUsername", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<Parameter> example = Example.of(parameter, exampleMatcher);
        Pageable parameterPage = PageRequest.of(page - 1, 20, Sort.by(Sort.Direction.DESC, "id"));
        Page<Parameter> all = parameterRepository.findAll(example, parameterPage);
        Map<String, Object> data = new HashMap<>();
        data.put("totalPage", all.getTotalPages());
        data.put("total", all.getTotalElements());
        data.put("courseParameter", all.getContent());
        return data;
    }

    @Override
    public String updateTopicNumber(TopicNumber topicNumber) {
        topicNumber.setId(1);
        topicNumberRepository.save(topicNumber);
        return "修改成功！";
    }

    @Override
    public Map getTeacherParameter(String grade, String courseCategory, String college) {
        Parameter parameter = parameterRepository.findByGradeAndCourseCategoryAndCollege(grade, courseCategory, college);
        Map<String, Object> data = new HashMap<>();
        data.put("parameter", parameter);
        return data;
    }

    @Override
    public TopicNumber getTopicNumber() {
        return topicNumberRepository.findById(1).orElse(null);
    }

    @Override
    public String addParameter(Parameter parameter) {
        if (parameter.getType().equals("课程设计")) {
            if (parameterRepository.findByCollegeAndGradeAndTypeAndCourseCategory(parameter.getCollege(), parameter.getGrade(), parameter.getType(), parameter.getCourseCategory()) != null) {
                return "该此参数已存在!";
            }
            String teacherUsername = userDetailsUtil.getUserDetails();
            parameter.setResTeacherUsername(teacherUsername);
            parameter.setMaxApply(10000);
            parameter.setMaxRecv(10000);
            parameter.setCourseMiniCategory(parameter.getGrade() + parameter.getCourseMajor() + parameter.getCourseCategory());
        } else {
            if (parameterRepository.findByCollegeAndGradeAndType(parameter.getCollege(), parameter.getGrade(), parameter.getType()) != null) {
                return "该此参数已存在!";
            }
        }

        if (parameterRepository.save(parameter) != null) {
            return "保存成功！";
        } else {
            return "保存失败！";
        }
    }

    @Override
    public String updateParameter(Parameter parameter) {
        String type = parameter.getType();
        String college = parameter.getCollege();
        String grade = parameter.getGrade();
        switch (type) {
            case "课程设计":
                List<Course> courses = courseRepository.findAllByCollegeAndGrade(college, grade);
                for (Course course : courses) {
                    course.setTaskStart(parameter.getTaskStart());
                    course.setTaskDdl(parameter.getTaskDdl());
                    course.setStuChooseStart(parameter.getStuChooseStart());
                    course.setStuChooseDdl(parameter.getStuChooseDdl());
                    course.setHomeworkDdl(parameter.getHomeworkDdl());
                    course.setMaxRecv(parameter.getMaxRecv());
                    course.setMaxApply(parameter.getMaxApply());
                }
                courseRepository.saveAll(courses);
                break;
            case "生产实习":
                List<Practice> practices = practiceRepository.findAllByCollegeAndGrade(college, grade);
                for (Practice practice : practices) {
                    practice.setTaskStart(parameter.getTaskStart());
                    practice.setTaskDdl(parameter.getTaskDdl());
                    practice.setStuChooseStart(parameter.getStuChooseStart());
                    practice.setStuChooseDdl(parameter.getStuChooseDdl());
                    practice.setTeaChooseStart(parameter.getTeaChooseStart());
                    practice.setTeaChooseDdl(parameter.getTeaChooseDdl());
                    practice.setHomeworkDdl(parameter.getHomeworkDdl());
                    practice.setMaxRecv(parameter.getMaxRecv());
                    practice.setMaxApply(parameter.getMaxApply());
                }
                practiceRepository.saveAll(practices);
                break;
            case "毕业设计":
                List<Design> designs = designRepository.findAllByCollegeAndGrade(college, grade);
                for (Design design : designs) {
                    design.setTaskStart(parameter.getTaskStart());
                    design.setTaskDdl(parameter.getTaskDdl());
                    design.setStuChooseStart(parameter.getStuChooseStart());
                    design.setStuChooseDdl(parameter.getStuChooseDdl());
                    design.setTeaChooseStart(parameter.getTeaChooseStart());
                    design.setTeaChooseDdl(parameter.getTeaChooseDdl());
                    design.setOpenDdl(parameter.getOpenDdl());
                    design.setTransDdl(parameter.getTransDdl());
                    design.setDesignDdl(parameter.getDesignDdl());
                    design.setHomeworkDdl(parameter.getHomeworkDdl());
                    design.setMaxRecv(parameter.getMaxRecv());
                    design.setMaxApply(parameter.getMaxApply());
                }
                designRepository.saveAll(designs);
                break;
            case "助教助研":
                List<Assistant> assistants = assistantRepository.findAllByCollegeAndGrade(college, grade);
                for (Assistant assistant : assistants) {
                    assistant.setTaskStart(parameter.getTaskStart());
                    assistant.setTaskDdl(parameter.getTaskDdl());
                    assistant.setStuChooseStart(parameter.getStuChooseStart());
                    assistant.setStuChooseDdl(parameter.getStuChooseDdl());
                    assistant.setTeaChooseStart(parameter.getTeaChooseStart());
                    assistant.setTeaChooseDdl(parameter.getTeaChooseDdl());
                    assistant.setMaxRecv(parameter.getMaxRecv());
                    assistant.setMaxApply(parameter.getMaxApply());
                }
                assistantRepository.saveAll(assistants);
                break;
            default:
                break;
        }
        parameterRepository.save(parameter);
        return "修改成功！";
    }

    @Override
    public String deleteParameter(Integer id) {
        parameterRepository.deleteById(id);
        return "删除成功！";
    }

    @Override
    public List<Parameter> getAllParameter() {
        return parameterRepository.findAll(Sort.by(Sort.Direction.DESC, "id"));
    }

    @Override
    public Parameter getOneParameter(String college, String grade, String type) {
        return parameterRepository.findByCollegeAndGradeAndType(college, grade, type);
    }

    @Override
    public String addColumn(Columns columns) {
        if (columnRepository.findByColumnName(columns.getColumnName()) != null) {
            return "该栏目已存在";
        }
        LocalDateTime now = LocalDateTime.now();
        columns.setAddTime(now);
        if (columnRepository.save(columns) != null) {
            return "保存成功！";
        } else {
            return "保存失败！";
        }
    }

    @Override
    public List<Columns> getAllColumn() {
        return columnRepository.findAll();
    }

    @Override
    public Columns getOneColumn(Integer id) {
        return columnRepository.findById(id).orElse(null);
    }

    @Override
    public String updateColumn(Columns column) {
        columnRepository.save(column);
        return "修改成功";
    }

    @Override
    public String deleteColumn(Integer id) {
        Columns column = columnRepository.findById(id).orElse(null);
        categoryRepository.deleteAllByColumnName(column.getColumnName());
        columnRepository.deleteById(id);
        return "删除成功！";
    }

    @Override
    @CacheEvict(cacheNames = "categoty", allEntries = true)
    public String addCategory(Category category) {
        Category samecategory = categoryRepository.findByCategoryName(category.getCategoryName());

        if ((samecategory != null) && (samecategory.getColumnName() == category.getColumnName())) {
            return "该类别已存在";
        }
        LocalDateTime now = LocalDateTime.now();
        category.setAddTime(now);
        if (categoryRepository.save(category) != null) {
            return "保存成功！";
        } else {
            return "保存失败！";
        }
    }

    @Override

    public List<Category> getAllCategory() {
        List<Category> categories = categoryRepository.findAll();
        categories.sort(Comparator.comparing(Category::getCategoryName));
        return categories;
    }

    @Override
    public Category getOneCategory(Integer id) {
        return categoryRepository.findById(id).orElse(null);
    }

    @Override
    @CacheEvict(cacheNames = "categoty", allEntries = true)
    public String updateCategory(Category category) {
        categoryRepository.save(category);
        return "修改成功!";
    }

    @Override
    @CacheEvict(cacheNames = "categoty", allEntries = true)
    public String deleteCategory(Integer id) {
        categoryRepository.deleteById(id);
        return "删除成功！";

    }

    @Override
    @Cacheable(cacheNames = "categoty")
    public List<Category> getCategoryByColumn(String columnName) {
        List<Category> categories = categoryRepository.findAllByColumnName(columnName);
        categories.sort(Comparator.comparing(Category::getCategoryName));
        return categories;
    }

    @Override
    public String addSubject(Subject subject) {
        LocalDateTime now = LocalDateTime.now();
        subject.setAddTime(now);
        if (subjectRepository.findByName(subject.getName()) != null) {
            return "该专题已存在";
        }
        if (subjectRepository.save(subject) != null) {
            return "保存成功！";
        } else {
            return "保存失败！";
        }
    }

    @Override
    public Subject getOneSubject(Integer id) {
        return subjectRepository.findById(id).orElse(null);
    }

    @Override
    public String updateSubject(Subject subject) {
        subjectRepository.save(subject);
        return "修改成功!";
    }

    @Override
    public List<Subject> getAllSubject() {
        return subjectRepository.findAll();
    }

    @Override
    public String deleteSubject(Integer id) {
        subjectRepository.deleteById(id);
        return "删除成功！";
    }
}
